<?php
namespace App\Services;
use App\Librarys\Wechatcrypts\Wxbizmsgcrypt;
use Illuminate\Support\Facades\Redis;
use GuzzleHttp\Client;
use App\Models\Workcorp;
use App\Services\WorkerrorService;
use Config,Log,Exception;

class WorkService
{
    // 自己企业解码
    public static function msgDecryptCorp($request)
    {
        $suite_id = empty($request->suite_id) ? "ww946aff83f14ce0fa" : $request->suite_id;
        $config = Config::get("weixin.work.".$suite_id);
        // 需要返回的明文
        $returnEchoStr = "";
        $wxcpt = new WXBizMsgCrypt($config["token"], $config["aes_key"], $config["corp_id"]);
        $errCode = $wxcpt->VerifyURL($request->msg_signature, $request->timestamp, $request->nonce, $request->echostr, $returnEchoStr);
        if ($errCode == 0) {
            return $returnEchoStr;
        } else {
            return "success";
        }
    }

    // 三方机构对外解密
    public static function msgDecryptSuit($request)
    {
        $suite_id = empty($request->suite_id) ? "ww946aff83f14ce0fa" : $request->suite_id;
        $config = Config::get("weixin.work.".$suite_id);
        $wxcpt = new WXBizMsgCrypt($config["token"], $config["aes_key"], $config["suite_id"]);
        $sPostData = $request->getcontent();
        $sMsg = "";
        $errCode = $wxcpt->DecryptMsg($request->msg_signature, $request->timestamp, $request->nonce, $sPostData,$sMsg);
        if ($errCode == 0) {
            return $sMsg;
        } else {
            return ["InfoType"=>"error"];
        };
    }

    // 客服消息解密
    public static function msgDecryptKefu($request)
    {
        $suite_id = empty($request->suite_id) ? "ww946aff83f14ce0fa" : $request->suite_id;
        $config = Config::get("weixin.work.".$suite_id);
        $wxcpt = new WXBizMsgCrypt($config["token"], $config["aes_key"], $config["suite_id"]);
        $sPostData = $request->getcontent();
        $sMsg = "";
        $errCode = $wxcpt->kefuDecryptMsg($request->msg_signature, $request->timestamp, $request->nonce, $sPostData,$sMsg);
        if ($errCode == 0) {
            return $sMsg;
        } else {
            return ["MsgType"=>"error"];
        };
    }

    // 获取企业三方应用凭证
    public static function getSuiteToken($suite_id="ww946aff83f14ce0fa")
    {
        $suite_id = empty($suite_id) ? "ww946aff83f14ce0fa" : $suite_id;
        $config = Config::get("weixin.work.".$suite_id);
        $suite_access_token = Redis::get("suite_access_token_".$config["suite_id"]);
        if (empty($suite_access_token)) {
            $suite_ticket = Redis::get("open_work_suite_ticket_".$config["suite_id"]);
            if (empty($suite_ticket)) return "";
            try {
                $client = new Client();
                $response = $client->request("POST", "https://qyapi.weixin.qq.com/cgi-bin/service/get_suite_token", ["json" => ["suite_id"=>$config["suite_id"],"suite_secret"=>$config["suite_secret"],"suite_ticket"=>$suite_ticket]],["timeout"=>3]);
                $body = $response->getBody()->getContents();
                $tokenInfo = json_decode($body,true);
                if (isset($tokenInfo["suite_access_token"])) {
                    $suite_access_token = $tokenInfo["suite_access_token"];
                    Redis::setex("suite_access_token_".$config["suite_id"],7100,$suite_access_token);
                    return $suite_access_token; 
                }
            } catch (Exception $e) {
                Log::info("getSuiteToken---------");
                Log::info($suite_id);
                Log::info($suite_ticket);
                Log::info($config);
                Log::info($e);
                Log::info("getSuiteToken---------");
            }
        }
        return $suite_access_token; 
    }

    // 获取企业access_token
    public static function getCropAccessTokenObject($corp_id)
    {
        $access_token = Redis::get("crop_access_token_".$corp_id);
        if (empty($access_token)) {
            $client = new Client();
            $kfcorp = Workcorp::getKfCorpsPermanentCode($corp_id);
            if (empty($kfcorp)) return "";
            $suite_access_token = self::getSuiteToken($kfcorp->suite_id);
            $response = $client->request("POST", "https://qyapi.weixin.qq.com/cgi-bin/service/get_corp_token?suite_access_token=".$suite_access_token, ["json" => ["auth_corpid"=>$corp_id,"permanent_code"=>$kfcorp->permanent_code]],["timeout"=>3]);
            $body = $response->getBody()->getContents();
            $token = json_decode($body,true);
            if (!isset($token["access_token"])) return ["status"=>"error","errcode"=>$token["errcode"],"access_token"=>""];
            $access_token = $token["access_token"];
            Redis::setex("crop_access_token_".$corp_id,7100,$access_token);
        }
        return ["status"=>"success","errcode"=>0,"access_token"=>$access_token];
    }

    // 获取企业access_token
    public static function getCropAccessToken($corp_id)
    {
        $access_token = Redis::get("crop_access_token_".$corp_id);
        if (empty($access_token)) {
            $client = new Client();
            $kfcorp = Workcorp::getKfCorpsPermanentCode($corp_id);
            if (empty($kfcorp)) return "";
            $suite_access_token = self::getSuiteToken($kfcorp->suite_id);
            $response = $client->request("POST", "https://qyapi.weixin.qq.com/cgi-bin/service/get_corp_token?suite_access_token=".$suite_access_token, ["json" => ["auth_corpid"=>$corp_id,"permanent_code"=>$kfcorp->permanent_code]],["timeout"=>3]);
            $body = $response->getBody()->getContents();
            $token = json_decode($body,true);
            if (!isset($token["access_token"])) return "";
            $access_token = $token["access_token"];
            Redis::setex("crop_access_token_".$corp_id,7100,$access_token);
        }
        return $access_token;
    }

    // 强制获取企业access_token
    public static function getCropAccessTokenFroch($corp_id)
    {
        $client = new Client();
        $kfcorp = Workcorp::getKfCorpsPermanentCode($corp_id);
        $suite_access_token = self::getSuiteToken($kfcorp->suite_id);
        $response = $client->request("POST", "https://qyapi.weixin.qq.com/cgi-bin/service/get_corp_token?suite_access_token=".$suite_access_token, ["json" => ["auth_corpid"=>$corp_id,"permanent_code"=>$kfcorp->permanent_code]],["timeout"=>3]);
        $body = $response->getBody()->getContents();
        $token = json_decode($body,true);
        if (!isset($token["access_token"])) return "";
        $access_token = $token["access_token"];
        Redis::setex("crop_access_token_".$corp_id,7100,$access_token);
        return $access_token;
    }

    // 获取预授权码
    public static function getPreAuthCode()
    {
        $suite_access_token = self::getSuiteToken();
        $client = new Client();
        $response = $client->request("GET", "https://qyapi.weixin.qq.com/cgi-bin/service/get_pre_auth_code?suite_access_token=".$suite_access_token,["timeout"=>3]);
        $body = $response->getBody()->getContents();
        $result = json_decode($body,true);
        return $result;
    }

    // 获取企业永久授权码
    public static function getPermanentCode($auth_code,$suite_id)
    {
        $suite_access_token = self::getSuiteToken($suite_id);
        $client = new Client();
        $response = $client->request("POST", "https://qyapi.weixin.qq.com/cgi-bin/service/get_permanent_code?suite_access_token=".$suite_access_token, ["json" => ["auth_code"=>$auth_code]],["timeout"=>3]);
        $body = $response->getBody()->getContents();
        return json_decode($body,true);
    }

    // 获取企业授权信息
    public static function getAuthInfo($auth_corpid,$permanent_code,$suite_id)
    {
        $suite_access_token = self::getSuiteToken($suite_id);
        $client = new Client();
        $response = $client->request("POST", "https://qyapi.weixin.qq.com/cgi-bin/service/get_auth_info?suite_access_token=".$suite_access_token, ["json" => ["auth_corpid"=>$auth_corpid,"permanent_code"=>$permanent_code]],["timeout"=>3]);
        $body = $response->getBody()->getContents();
        return json_decode($body,true);
    }

    // 通讯录单个搜索
    public static function contactSearch($corp_id,$query_word,$suite_id)
    {
        $suite_access_token = self::getSuiteToken($suite_id);
        $client = new Client();
        $response = $client->request("POST", "https://qyapi.weixin.qq.com/cgi-bin/service/contact/search?provider_access_token=".$suite_access_token, ["json" => ["auth_corpid"=>$corp_id,"query_word"=>$query_word,"full_match_field"=>1]],["timeout"=>3]);
        $body = $response->getBody()->getContents();
        return json_decode($body,true);
    }

    // 三方获取客户基本信息
    public static function kfCustomerInfo($corp_id,$external_userid_list)
    {
        $access_token = self::getCropAccessToken($corp_id);
        if (empty($access_token)) return ["errcode"=>"10001","msg"=>"获取AccessToken失败,请联系客服处理！"];
        $client = new Client();
        $response = $client->request("POST", "https://qyapi.weixin.qq.com/cgi-bin/kf/customer/batchget?access_token=".$access_token, ["json" => ["external_userid_list"=>$external_userid_list,"need_enter_session_context"=>1]],["timeout"=>3]);
        $body = $response->getBody()->getContents();
        return json_decode($body,true);
    }

    // 获取视频号绑定状态
    public static function getCorpQualification($corp_id)
    {
        $access_token = self::getCropAccessToken($corp_id);
        if (empty($access_token)) return ["errcode"=>"10001","msg"=>"获取AccessToken失败,请联系客服处理！"];
        $client = new Client();
        $response = $client->request("GET", "https://qyapi.weixin.qq.com/cgi-bin/kf/get_corp_qualification?access_token=".$access_token,["timeout"=>3]);
        $body = $response->getBody()->getContents();
        return json_decode($body);
    }

    // 上传临时素材
    public static function mediaUpload($corp_id,$type,$filepath)
    {
        $accessTokenInfo = self::getCropAccessTokenObject($corp_id);
        if ($accessTokenInfo["errcode"] != 0) return $accessTokenInfo;
        $client = new Client();
        $file_name = md5(time());
        $response = $client->request('POST',"https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=".$accessTokenInfo["access_token"]."&type=".$type, [
            'multipart' => [
                [
                    'name' => 'media',
                    "filename"=>$file_name,
                    'contents' =>file_get_contents($filepath),
                    'headers' => [
                        'Content-Type' => 'image/jpg'
                    ]
                ]
            ]
        ],["timeout"=>3]);
        $body = $response->getBody()->getContents();
        return json_decode($body,true);
    }

    // 上传图片
    public static function mediaUploadImg($corp_id,$filepath)
    {
        $accessTokenInfo = self::getCropAccessTokenObject($corp_id);
        if ($accessTokenInfo["errcode"] != 0) return $accessTokenInfo;
        $url = "https://qyapi.weixin.qq.com/cgi-bin/media/uploadimg?access_token=".$accessTokenInfo["access_token"];

        $client = new Client();
        $file_name = md5(time());
        $response = $client->request("POST",$url, [
            'multipart' => [
                [
                    'name' => 'media',
                    "filename"=>$file_name,
                    'contents' =>file_get_contents($filepath),
                    'headers' => [
                        'Content-Type' => 'image/jpg'
                    ]
                ]
            ]
        ],["timeout"=>3]);
        $body = $response->getBody()->getContents();
        return json_decode($body,true);
    }

    // 获取临时素材
    public static function mediaGet($corp_id,$media_id)
    {
        $accessTokenInfo = self::getCropAccessTokenObject($corp_id);
        if ($accessTokenInfo["errcode"] != 0) return $accessTokenInfo;
        $client = new Client();
        $response = $client->request("GET", "https://qyapi.weixin.qq.com/cgi-bin/media/get?access_token=".$accessTokenInfo["access_token"]."&media_id=".$media_id,["timeout"=>3]);
        $body = $response->getBody()->getContents();
        return json_decode($body);
    }

    // 获取高清语音素材
    public static function mediaGetJsSdk($corp_id,$media_id)
    {
        $accessTokenInfo = self::getCropAccessTokenObject($corp_id);
        if ($accessTokenInfo["errcode"] != 0) return $accessTokenInfo;
        $client = new Client();
        $response = $client->request("GET", "https://qyapi.weixin.qq.com/cgi-bin/media/get/jssdk?access_token=".$accessTokenInfo["access_token"]."&media_id=".$media_id,["timeout"=>3]);
        $body = $response->getBody()->getContents();
        return json_decode($body);
    }

    // 批量获取客户详情
    public static function getByUser($corp_id,$userid_list)
    {
        $access_token = self::getCropAccessToken($corp_id);
        if (empty($access_token)) return ["errcode"=>"10001","msg"=>"获取AccessToken失败,请联系客服处理！"];
        $client = new Client();
        $response = $client->request("POST", "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/batch/get_by_user?access_token=".$access_token."&userid_list=".$userid_list,["timeout"=>3]);
        $body = $response->getBody()->getContents();
        return json_decode($body);
    }

    // 获取访问用户身份
    public static function getUserInfo3rd($code,$suite_id)
    {
        $suite_access_token = self::getSuiteToken($suite_id);
        if (empty($suite_access_token)) return ["errcode"=>"10001","errmsg"=>"获取SuiteAccessToken失败,请联系客服处理！"];
        $client = new Client();
        $response = $client->request("GET", "https://qyapi.weixin.qq.com/cgi-bin/service/getuserinfo3rd?suite_access_token=".$suite_access_token."&code=".$code,["timeout"=>3]);
        $body = $response->getBody()->getContents();
        return json_decode($body,true);
    }

}
